/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controller;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.User;
import utilities.HtmlTable;
import utilities.ParametersValidator;
import utilities.SafeSessionAccess;
import webSiteDataStore.SQLExecute;
import webSiteDataStore.SafeFreeResource;

/**
 *
 * @author gsagy
 */
public class Communities extends HttpServlet
{
    private static String table = "Communities";
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */

    private boolean doCreateCommunity(HttpServletRequest request)
    {
        // Create the community.
        boolean success = ParametersValidator.ValidateUserParameters(request, "name", "description");
        if (!success)
            return success;
        
        String communityName = request.getParameter("name");
        HttpSession session = request.getSession(false);
        int communityCreator = ((User)(SafeSessionAccess.getAttribute(session, "user"))).getUserId();
        Date communityCreationTime = Calendar.getInstance().getTime();
        String communityDescription = request.getParameter("description");

        ArrayList<String> columns = new ArrayList<String>();
        columns.add("name");
        columns.add("creator");
        columns.add("creationTime");
        columns.add("description");

        ArrayList<Object> values = new ArrayList<Object>();
        values.add(communityName);
        values.add(communityCreator);
        values.add(communityCreationTime);
        values.add(communityDescription);

        if (SQLExecute.Insert(table, columns, values) == true)
        {
            // Get this communitie's id.
            columns = new ArrayList<String>();
            columns.add("communityId");

            String where = "name = ?";
            ArrayList<String> whereValues = new ArrayList<String>();
            whereValues.add(communityName);

            PreparedStatement preparedStatement = SQLExecute.Select(table, columns, where, whereValues);
            ResultSet resultSet = null;
            int communityId = -1;

            try
            {
                resultSet = preparedStatement.getResultSet();
                int countOfRows = 0;
                if (resultSet.last())
                    resultSet.getRow();

                if (countOfRows != 1)
                    throw new Exception((new StringBuilder(countOfRows).append(" affected by an attempt to insert a new community")).toString());

                communityId = resultSet.getInt("Id");
            }
            catch (Exception ex)
            {
                Logger.getLogger(Communities.class.getName()).log(Level.SEVERE, null, ex);
                resultSet = null;
            }
            finally
            {
                SafeFreeResource.closeResultSet(resultSet);
                SafeFreeResource.closeStatement(preparedStatement);
                try
                {
                    SafeFreeResource.closeConnection(preparedStatement.getConnection());
                }
                catch (SQLException ex)
                {
                    Logger.getLogger(Communities.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            if (communityId != -1)
            {
                // Associate the creator with this community.
                table = "CommunityUsers";

                columns = new ArrayList<String>();
                columns.add("communityId");
                columns.add("userId");

                values = new ArrayList<Object>();
                values.add(communityId);
                values.add(communityCreator);

                SQLExecute.Insert(table, columns, values);
                success = true;
            }
        }

        return success;
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    {
        ParametersValidator.ValidateProgrammerParameters(request, "mode");
        
        String mode = request.getParameter("mode");
        String pageTitle = "";
        if (mode.equals("docreate"))
        {
            // TODO: handle this failure by messaging the user
            doCreateCommunity(request);
            mode = "view";
        }
        else if (mode.equals("create"))
        {
            pageTitle = "Create a community";
        }        

        if (mode.equals("view"))
        {
            pageTitle   = "View communities";
            PreparedStatement   preparedStatement = null;
            ResultSet           resultSet = null;
            String              htmlTable = "";
            try
            {
                preparedStatement   = SQLExecute.Select(table);
                resultSet           = preparedStatement.getResultSet();
                htmlTable           = HtmlTable.FromResultSet(resultSet);
            }
            catch (Exception ex)
            {
                Logger.getLogger(Communities.class.getName()).log(Level.SEVERE, null, ex);
            }
            finally
            {
                SafeFreeResource.closeResultSet(resultSet);
                SafeFreeResource.closeStatement(preparedStatement);
            }
            
            HttpSession session = request.getSession(false);
            SafeSessionAccess.setAttribute(session, "communitiesHtmlTable", htmlTable);
        }
        
        request.setAttribute("presentationMedium", "desktop");
        request.setAttribute("pageTitle", pageTitle);
        String nextPage = "/communities.jsp?mode=" + mode;
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextPage);
        dispatcher.forward(request, response);
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
